package net.cloudsun.graph.puzzle;

import net.cloudsun.graph.core.EdgeList;
import net.cloudsun.graph.core.UnweightedEdgeList;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 拼图存储
 *
 * @author Ryan
 * @since 1.0
 */
public class JigsawStore {


    /**
     * 全集中取出有解的半集
     */
    public static void saveVertex() {
        JigsawState[] halfVertices = getHalfVertices();
        try (OutputStream outputStream = Files.newOutputStream(Paths.get("jigsaw-vertices.dat"));
             PrintStream oos = new PrintStream(outputStream)) {
            for (JigsawState state : halfVertices) {
                // 把这些全部转为字符串
                // 然后按行存储
                String line = state.toSingleLineString();
                oos.println(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        // 此外，要把边也存储进去
        Map<JigsawState, Integer> map = JigsawGraph.map(halfVertices);
        UnweightedEdgeList[] edgeLists = JigsawGraph.getEdgeLists(halfVertices, map);
        try (OutputStream outputStream = Files.newOutputStream(Paths.get("jigsaw-edges.dat"));
             PrintStream oos = new PrintStream(outputStream)) {

            for (UnweightedEdgeList edgeList : edgeLists) {
                oos.println();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static JigsawState[] getHalfVertices() {
        JigsawGraph jigsawGraph = new JigsawGraph();
        JigsawState first = new JigsawState(Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8));
        Set<Integer> bfs = jigsawGraph.bfs(first);
        JigsawState[] vertices = jigsawGraph.getVertices();
        return bfs.stream().sorted().map(x -> vertices[x]).collect(Collectors.toList())
                .toArray(new JigsawState[0]);
    }
}
